package com.akino.gulimall.ware.service.impl;

import com.akino.common.exception.NoStockException;
import com.akino.common.to.mq.OrderTo;
import com.akino.common.to.mq.StockDetailTo;
import com.akino.common.to.mq.StockLockedTo;
import com.akino.common.utils.R;
import com.akino.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.akino.gulimall.ware.entity.WareOrderTaskEntity;
import com.akino.gulimall.ware.feign.OrderFeignService;
import com.akino.gulimall.ware.service.WareOrderTaskDetailService;
import com.akino.gulimall.ware.service.WareOrderTaskService;
import com.akino.gulimall.ware.vo.OrderItemVo;
import com.akino.gulimall.ware.vo.OrderVo;
import com.akino.gulimall.ware.vo.SkuHasStockVo;
import com.akino.gulimall.ware.vo.WareSkuLockVo;
import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.akino.common.utils.PageUtils;
import com.akino.common.utils.Query;

import com.akino.gulimall.ware.dao.WareSkuDao;
import com.akino.gulimall.ware.entity.WareSkuEntity;
import com.akino.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    OrderFeignService orderFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(sku -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            // 查询当前sku的总库存量
            Long count = baseMapper.getSkuStock(sku);
            vo.setSkuId(sku);
            vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * @param vo 要锁库存的商品信息和该订单的订单号
     * @return
     *
     * 库存解锁场景：
     * 1.下订单成功，订单过期没有支付被系统自动取消，被用户手动取消
     * 2.下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚（之前锁定的库存就要解锁）
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单的详情（方便追溯）
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        // 1.找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        Boolean allLock = true;
        // 2.锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds==null || wareIds.size()==0){
                // 没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            // 如果每个商品锁定成功，将当前商品锁定了几件的工作单记录发送给MQ
            // 如果锁定失败，前面保存的工作单信息就回滚
            for (Long wareId : wareIds) {
                // 成功返回1，否则就是0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if (count==1){
                    // 当前仓库锁定成功
                    skuStocked = true;
                    // TODO 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity detailEntity
                            = new WareOrderTaskDetailEntity(null,skuId,"",hasStock.getNum(),taskEntity.getId(),wareId,1);
                    orderTaskDetailService.save(detailEntity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity,stockDetailTo);
                    lockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange",
                            "stock.locked",
                            lockedTo);

                    break;
                } else {
                    // TODO 当前仓库锁定失败，重试下一个仓库
                }
            }
            if (skuStocked==false){
                // 当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        // 全部锁定成功
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        Long detailId = detail.getId();
        // 1.查询数据库关于这个订单的锁定库存信息：
        // 没有信息 -> 库存锁定失败，库存回滚了，这种情况无需解锁
        // 有信息 -> 库存锁定成功，看订单情况 -> 没有订单，必须解锁；存在订单，系统取消订单，解锁库存；存在订单，系统没有取消订单，不能解锁库存
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId != null){
            // 解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            // 根据订单号查询订单状态
            R r = orderFeignService.getOrderStatusByOrderSn(orderSn);
            if (r.getCode()==0){
                // 订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>(){});
                if (data==null||data.getStatus()==4){
                    // 订单不存在
                    // 订单已经被取消了，才能解锁库存
                    if (byId.getLockStatus()==1) {
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                // 消息拒绝以后重新放回队列里面，让别人继续消费解锁
                throw new RuntimeException("远程服务失败");
            }
        } else {
            // 无需解锁
        }

    }

    // 防止订单服务卡顿导致订单状态消息一直改不了，库存消息优先到期，查订单状态为新建状态，什么都不做，导致卡顿的订单永远无法解锁库存
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        // 查询库存解锁状态，防止重复解锁
        WareOrderTaskEntity task = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        // 按照工作单找到所有没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", id)
                        .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }

    /**
     * 处理库存锁定释放的请求
     */
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        StockDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        Long detailId = detail.getId();
        // 1.查询数据库关于这个订单的锁定库存信息：
        // 没有信息 -> 库存锁定失败，库存回滚了，这种情况无需解锁
        // 有信息 -> 库存锁定成功，看订单情况 -> 没有订单，必须解锁；存在订单，系统取消订单，解锁库存；存在订单，系统没有取消订单，不能解锁库存
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId != null){
            // 解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            // 根据订单号查询订单状态
            R r = orderFeignService.getOrderStatusByOrderSn(orderSn);
            if (r.getCode()==0){
                // 订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>(){});
                if (data==null||data.getStatus()==4){
                    // 订单不存在
                    // 订单已经被取消了，才能解锁库存
                    unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }
            } else {
                // 消息拒绝以后重新放回队列里面，让别人继续消费解锁
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }
        } else {
            // 无需解锁
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }

    }

    /**
     * 解锁库存
     * @param skuId 要解锁的商品的skuId
     * @param wareId 要解锁的仓库的id
     * @param skuNum 要解锁的商品数量
     * @param detailId 库存工作单的id
     */
    private void unLockStock(Long skuId, Long wareId, Integer skuNum, Long detailId) {
        // 库存解锁
        wareSkuDao.unlockStock(skuId,wareId,skuNum);
        // 更新库存工作单的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(detailId);
        detailEntity.setLockStatus(2); // 变为已解锁
        orderTaskDetailService.updateById(detailEntity);
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}